﻿/**
 * 
 */
require(['jquery',
         'global',
         'module/util',
         'module/datatables',
         'bootbox.min',
         'module/ajax',
         'jquery.validate',
         'bootstrap',
         'pixeladmin',
         'requirejs/domready!'], 
	function($, global, util, datatables, bootbox){
	window.PixelAdmin.start();
	
	
	var adminuserTable = null;

	/**分页查询start**/
	var checkTr = function(data,type,full){
    };

    var operate = function(data,type,full){
    	if(full.roleName.indexOf("superadmin") >= 0)
    		return "";
    	
    	var message = '<a href="javascript:void(0)" class="editAdminUser" data-id="'+full.id+'">编辑</a>'
    	+'&nbsp;|&nbsp;<a href="javascript:void(0)" class="groupManage" data-id="'+full.id+'"data-name="'+full.name+'">用户组管理</a>'
	    +'&nbsp;|&nbsp;<a href="javascript:void(0)" class="resetPassword" data-id="'+full.id+'">重置密码</a>';
    	if(full.status == 'A'){
    		message += '&nbsp;|&nbsp;<a href="javascript:void(0)" class="deleteOne" data-id="'+full.id+'">禁用</a>';
    	} else {
    		message += '&nbsp;|&nbsp;<a href="javascript:void(0)" class="reuseOne" data-id="'+full.id+'">复用</a>';
    	}
    	if(full.workStatus == 0){
    		message += '&nbsp;|&nbsp;<a href="javascript:void(0)" class="change_WorkStatus" data-id="'+full.id+'">暂停工作</a>';
    	} else {
    		message += '&nbsp;|&nbsp;<a href="javascript:void(0)" class="change_WorkStatus" data-id="'+full.id+'">开启工作</a>';
    	}
    	return message;

    };
    
	var _rendarTable = function(){
		var options = {};
		options.tableId = '#jq-datatables-example';
		options.aaSorting = [[1,"asc"]];
		options.sAjaxSource = global.context+"/web/adminuser/searchbyCon";
		options.functionList = {"checkTr":checkTr,"operate":operate,"userType":function(a,b){
			return dict.get("userType",1)
		}};
        adminuserTable = datatables.init(options);
		var result = util.getSearchData("#search-area") ;
		adminuserTable.setParams(result);
		
		$('#jq-datatables-example').css('width', "100%");
		return adminuserTable.create();
	};
	
	var bindEvent = function(){
		$("#search-btn").on("click",function(){
			adminuserTable.setParams(util.getSearchData('#search-area'));
			adminuserTable.invoke("fnDraw");
		});
		$("#do-reset").on("click",function(){
			$('#search-area input[type=text]').val('');	
			$('#search-area select option:first-child').prop('selected',true);
		});
		$('body').on('click', '.deleteOne', function(){//停用确认
			var target = $(this);
			bootbox.confirm({
				buttons: {  
		            confirm: {  
		                label: '确认',  
		                className: 'btn-myStyle'  
		            },  
		            cancel: {  
		                label: '取消',  
		                className: 'btn-default'  
		            }  
	      		 },  
				message: "确认要停止使用该用户吗?",
				callback: function(isOk) {
					if(isOk){
						$.ajax({
					        'url' : global.context+'/web/adminuser/doDelete/'+target.data('id'),
					        'type' : 'DELETE',
					        'dataType' : 'json',
					        'success' : function(result) {
					        	if(result.code=='ACK'){
					        		adminuserTable.invoke("fnStandingRedraw");// 停用成功后，refresh列表
					        	}
					        },
					        'error' : function() {
					        }
						});
					}
				},
				className: "bootbox-sm"
			});	
		});
		
		$('body').on('click', '.reuseOne', function(){//复用确认
			var target = $(this);
			bootbox.confirm({
				buttons: {  
		            confirm: {  
		                label: '确认',  
		                className: 'btn-myStyle'  
		            },  
		            cancel: {  
		                label: '取消',  
		                className: 'btn-default'  
		            }  
	      		 },  
				message: "确认重新使用该用户吗?",
				callback: function(isOk) {
					if(isOk){
						$.ajax({
					        'url' : global.context+'/web/adminuser/doReuse/'+target.data('id'),
					        'type' : 'POST',
					        'dataType' : 'json',
					        'success' : function(result) {
					        	if(result.code=='ACK'){
					        		adminuserTable.invoke("fnStandingRedraw");// 复用成功后，refresh列表
					        	}
					        },
					        'error' : function() {
					        }
						});
					}
				},
				className: "bootbox-sm"
			});	
		});
		
		
		$('body').on('click','.change_WorkStatus',function(){
			var target=$(this);
			var id=target.attr("data-id");
			$.ajax({
	            url: global.context+'/web/adminuser/changeWorkStatus/'+id,
	            type: "GET",
	            cache:false,
	            dataType: "json",
	            success: function(result) {
	                if(result){
	                    if(result.code != "NACK"){
	                    	adminuserTable.invoke("fnStandingRedraw");
	                    	if(result.data=="暂停工作")
	                    		$("#changeWorkStatus").html("<i class='dropdown-icon fa fa-pause'></i>&nbsp;&nbsp;"+result.data);
	                    	else
	                    		$("#changeWorkStatus").html("<i class='dropdown-icon fa fa-play'></i>&nbsp;&nbsp;"+result.data);
	                    }
	                }
	            }
	        });
		});
		
		$("#search-area").on("keydown",function(e){
			if(e.which == 13){
				$("#adminuser-search-btn").trigger("click");
				return false;
			}
		});
	};
	
	var init = function(){
		_rendarTable();
		bindEvent();
	};
	
	init();
	
	/**分页查询end**/
	//点击新增，显示新增表单
	$('body').on('click', '#newBtn', function(){
		$("#modal-title").html("添加用户");
		$("#username").removeAttr("disabled");
		$("#username").removeAttr("readonly");
		$("#adminUserForm input:not([type='checkbox'])").val("");
    	var checkboxs = $("#adminUserForm").find('input[type=checkbox]');
    	for(var i=0;i<checkboxs.length;i++){	
            checkboxs.eq(i)[0].checked=false;
        }
		var me = $(this);
		$('#adminUserForm').attr("action", global.context+"/web/adminuser/doAdd") ;
		adminUserForm.resetForm();
		$("#adminUserModal").find("input[type='text'],select").removeClass('highlight-error');
		$('#adminUserModal').modal('show');
		
	});
	//点击用户组管理，显示选中用户组框架
	$('body').on('click', '.groupManage', function(){
		var me = $(this);
		$('#chosen_userId').val(me.data('id'));
		$('#chosen_userName').val(me.data('name'));
		
		$.ajax({
	        'url' :  global.context+"/web/adminuser/getgroupList",
	        'data':{
	        	userId:me.data('id')
	        },
	        'type' : 'get',
	        'dataType' : 'json',
	        'success' : function(result) {
                    if(result.code != "NACK" ){
                    	
                        var groupList = result.data;
                        var groupContainer = $('#chosen-group-content');
                        groupContainer.empty();
                        $(":checkbox","#panel-user-content").prop('checked',false);
                        
                        if(groupList!=null && groupList.length>0){
                        	for(var i=0;i<groupList.length;i++){
                        		groupContainer.append ('<label class="w-3 col-sm-4"><input id="group_chosen_'+groupList[i].id+'" type="checkbox" class="chosen" style="float: left;" value="'+groupList[i].id+'" /> <span style="margin: 2px 0 2px 5px; float: left;">'+groupList[i].name+'</span></label>')
                        		$("#group_chosen_"+groupList[i].id)[0].checked=true;
	                            $("#group_"+groupList[i].id)[0].checked=true;
                        	}
                        }
                       
                    }
	        }
		});
		
		$('#workGroupModal').modal('show');
	});
	 //用户组列表，用户组信息
    $("#J_groupContainer").on('click','.unchosen',function(e){
        var permissionsContainer = $('#chosen-group-content');
        var refId=$(this).val();
        var value=$(this).next().html();
        var newvalue=$(this).next().attr('title');
        var choseninp=$("#group_chosen_"+refId);
        $("#modal-title").html("选择用户组");
        if(choseninp.length<=0){
        	if(value.length<10) {
        		permissionsContainer.append('<div class="col-sm-3"><div class="checkbox"><label style="width:100%;text-align:left;"><input id="group_chosen_'+refId+'" type="checkbox" class="chosen" value="'+refId+'" checked/><span>'+value+'</span></label></div></div>');
            } else {
        		permissionsContainer.append('<div class="col-sm-3"><div class="checkbox"><label style="width:100%;text-align:left;"><input id="group_chosen_'+refId+'" type="checkbox" class="chosen" value="'+refId+'" checked/> <span data-toggle="tooltip" data-placement="bottom"'+ 'title="'+newvalue+'" >'+value.substring(0,7)+'...</span></label></div></div>');
        	}
        }else{
        	choseninp.parent().parent().parent().remove();
        }
        
      });
    
  //已选用户
    $("#J_user_chosen").on('click','.chosen',function(e){
    	var refId=$(this).val();
    	 $('#group_'+refId)[0].checked=false;
        $(this).parent().parent().parent().remove();
        
      });
    $('#workGroupModal').on('click','.J_groupsave',function(e){
        var permissions = $('#chosen-group-content').find('input[type=checkbox]');
        var checked = permissions.filter(':checked');
        var grantedGroup = [];
        if(checked.length>0){
            for(var i=0;i<checked.length;i++){
            	grantedGroup.push(checked.eq(i).val());
            }
        }
        $.ajax({
            url: global.context+'/web/adminuser/assignGroup',
            type: "POST",
            cache:false,
            data: JSON.stringify({
            	userId:$('#chosen_userId').val(),
            	refId:grantedGroup.join(',')
            }),
            
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            success: function(result) {
                if(result){
                    if(result.code != "NACK"){
                    	$('#workGroupModal').modal('hide');
                    	adminuserTable.invoke("fnStandingRedraw");
                    }else{
                    }
                }
            }
        });
        
    });
    
	
	/**分页查询end**/
	//点击编辑，显示编辑表单
	$('body').on('click', '.editAdminUser', function(){
		$("#username").attr("readonly","readonly");
		$("#username").attr("disabled","disabled");
		$("#modal-title").html("编辑用户");		
		var me = $(this);
		$('#adminUserForm').attr("action", global.context+"/web/adminuser/doEdit/"+me.data('id'));
		
		$.ajax({
	        'url' :  global.context+"/web/adminuser/toEdit/"+me.data('id'),
	        'data':'',
	        'type' : 'get',
	        'dataType' : 'json',
	        'success' : function(adminUser) {
	        	var checkboxs = $("#roleLists").find('input[type=checkbox]');
	        	for(var i=0;i<checkboxs.length;i++){	
                    checkboxs.eq(i)[0].checked=false;
                }
	        	var roleList = adminUser.roleList ;
	        	if(roleList!=null && roleList.length>0){
                    for(var i=0;i<roleList.length;i++){
                    	 $("#user_"+roleList[i].roleId).prop("checked","checked");
                    }
                }
	        	$.each(roleList, function(index,role ){
	            		/*$("#roleLists").append('<label class="w-5"><input  type="checkbox" style="float:left;" value="'+role.id+'" />'+
	            				'<span style="margin: 2px 0 2px 5px; float: left;">'+role.roleName+'</span></label>');*/
	             });
	        	$("#username").val(adminUser.username);
	        	$("#name").val(adminUser.name);        	
	        	$("#email").val(adminUser.email);
	        	$(".mobile").val(adminUser.mobile);
	        	adminUserForm.resetForm();
	        	$("#adminUserModal").find("input[type='text'],select").removeClass('highlight-error');
	        	$('#adminUserModal').modal('show');
	        },
	        'error': function(request) {
                $('#alertsDanger').find(".modal-body").text(request.statusText);
				$('#alertsDanger').modal();
            },
		});
	});
	
	$('body').on('click', '.resetPassword', function(){
		$(".modal-title").html("密码重置");		
		var me = $(this);
		$('#resetPasswordForm').attr("action", global.context+"/web/adminuser/doResetPassword/"+me.data('id'));
		
		$.ajax({
	        'url' :  global.context+"/web/adminuser/toResetPassword/"+me.data('id'),
	        'data':'',
	        'type' : 'get',
	        'dataType' : 'json',
	        'success' : function(adminUser) {
	        	$("#resetUserName").val(adminUser.username);
	        	$("#resetname").val(adminUser.name); 
	        	resetPasswordForm.resetForm();
	        	$("#resetPasswordModal").find("input[type='password']").val('');
	    		$("#resetPasswordModal").find("input[type='password'],select").removeClass('highlight-error');
	        	$('#resetPasswordModal').modal('show');
	        },
	        'error': function(request) {
                $('#alertsDanger').find(".modal-body").text(request.statusText);
				$('#alertsDanger').modal();
            },
		});
	});
	
	var resetPasswordForm = $('#resetPasswordForm').validate({
		onkeyup : false,
		rules:{
			newPassword:{
				required: true,
				rangelength: [4,30]
			}
		},
		messages : {
			newPassword:{
	        	   required: "密码不能为空",
	        	   rangelength : $.format("密码长度：{0}-{1}个字符")
	        }
		},
			
		submitHandler: function(form) {
			util.ajax_submit(form).complete(function(xhr) {
				var result = $.parseJSON(xhr.responseText);
				if(result.code=="ACK"){
				}else{
					$.pnotify({
						type:'error',
						title:result.message
					 });
				}
				$("#resetPasswordModal").modal('hide');
				$("#resetPasswordModal input[type='password']").val('');
			});
	    },
	    errorPlacement:function(error, element){//自定义错误提示放置的位置
	    	var $errorPanel = '<div class="validate-error-panel"></div>';
	    	element.closest(".info_item").after($errorPanel);
	    	error.appendTo(element.closest(".info_item").next('.validate-error-panel'));
	    },
	    highlight: function(element, errorClass) {  
	    	$(element).addClass('highlight-error');//未通过验证的元素高亮
        },
        unhighlight: function(element, errorClass) {  
	    	$(element).removeClass('highlight-error');//通过验证去掉高亮
        },
        success: function(label) {  
        }  
	});
	
	// 添加为正整数的验证规则
	$.validator.addMethod("checkNumber", function(value, element) {
		return this.optional(element) || /^[1-9]\d*$/.test(value);
	});
	//表单校验加提交
	var adminUserForm = $('#adminUserForm').validate({
		onkeyup : false,
		rules:{
			username:{
            	required: true,
            	rangelength: [5,30]
            },
            name:{
            	required: true,
            	rangelength: [2,30],
            },
            userType:{
            	required: true
            },
			mobile:{
	    		required : true,
	    		rangelength: [11,11],
	    		number : true
	    	},
	    	email : {
	    		required :true,
	    		email : true
	    	},
	    	roleList:{
	    		required :true,
	    		minlength:1
	    	}
	    },
	    messages : {
	    	username:{
	        	   required: "用户名不能为空",
	        	   rangelength : $.format("用户名长度：{0}-{1}个字符")
	        },
	    	name:{
	        	   required: "姓名不能为空",
	        	   rangelength : $.format("姓名长度：{0}-{1}个字符"),
	        },
	        roleList:{
	        	required: "至少选择一种角色",
	    		minlength: "至少选择一种角色"
	    	},
	    	mobile : {
	    		required : '手机号码不能为空',
	    		rangelength: $.format("手机号码为11位数字"),
	    		number : '手机号码只能是数字'
	    	},
	    	email : {
	    		required : 'email不能为空',
	    		email : '请输入正确的email格式'
	    	}
	    },
		submitHandler: function(form) {
			var mobile=$(form).find("#mobile").val();
			var roles = $('#roleLists').find('input[type=checkbox]');
	        var checked = roles.filter(':checked');
	        var grantedRoles = [];
	        if(checked.length>0){
	            for(var i=0;i<checked.length;i++){
	            	grantedRoles.push(checked.eq(i).val());
	            }
	        }
	        $("#addOrupdateBtn").attr('disabled',"true");
			 $.ajax({
		            url:  $(form).attr('action'),
		            type: "post",
		            cache:false,
		            data: JSON.stringify({
		            	username:$('#username').val(),
		            	name:$('#name').val(),
		            	email:$('#email').val(),
		            	mobile:mobile,
		            	roleIds:grantedRoles.join(',')
		            }),
		            contentType : 'application/json; charset=UTF-8',
		            dataType: "json",
		            success: function(result) {
		                if(result.code == "ACK" || result.code == "ACK_NO_MESSAGE"){
		                    	adminuserTable.invoke("fnDraw");
		                    	$("#adminUserModal").modal('hide');
		                    	$("#adminUserModal input[type='text']").val('');
		                    	$("#adminUserModal #type").empty();
		                    }
		    				
		            }
		        });
			 $("#addOrupdateBtn").removeAttr("disabled");
			
	    },
	    errorPlacement:function(error, element){//自定义错误提示放置的位置
	    	var $errorPanel = '<div class="validate-error-panel"></div>';
	    	element.closest(".info_item").after($errorPanel);
	    	error.appendTo(element.closest(".info_item").next('.validate-error-panel'));
	    },
	    highlight: function(element, errorClass) {  
	    	$(element).addClass('highlight-error');//未通过验证的元素高亮
        },
        unhighlight: function(element, errorClass) {  
	    	$(element).removeClass('highlight-error');//通过验证去掉高亮
        },
        success: function(label) {  
        }  
	});
	
	//关闭modal框
	$("#adminUserModal").on('click','.close',function(){
		adminUserForm.resetForm();
		$("#adminUserModal").find("input[type='text'],select").removeClass('highlight-error');
	});
	
	
});
